package com.example.fragmentmanager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.example.fragmentmanager.callback.IFragmentCallBack;

/**
 * 点击按钮实现fragment的切换
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button1=findViewById(R.id.btn1);
        Button button2=findViewById(R.id.btn2);
        button1.setOnClickListener((view)->{
            switch (view.getId()){
                case R.id.btn1:
                    Bundle bundle=new Bundle();
                    bundle.putString("msg","我想把安卓学好");
                    BlankFragment1 blankFragment1=new BlankFragment1();

                    blankFragment1.setiFragmentCallBack(new IFragmentCallBack() {
                        @Override
                        public void sendMagToActivity(String string) {
                            Toast.makeText(MainActivity.this,string,Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public String getMsgFromActivity(String msg) {
                            return "hello i am from activity";
                        }
                    });


                    blankFragment1.setArguments(bundle);
                    replaceFragment(blankFragment1);
                    break;

            }
        });

        button2.setOnClickListener((view)->{
            switch (view.getId()){
                case R.id.btn2:
                    replaceFragment(new ItemFragment());

            }
        });
    }

    /**
     * FragmentManager创建事务提交fragment切换
     * @param fragment
     */
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager=getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragmentlayout,fragment);
        transaction.commit();
    }
}